<template>
	<picker :value="value" mode="multiSelector" :range="range" range-key="name" @change="change"
		@columnchange="columnchange">
		<fui-form-item label="城市/部门:" arrow highlight :bottom-border="true" :padding="['32rpx', '30rpx']">
			<view v-if="value.length === 0" class="fs-color__label">请选择</view>
			<view v-else>{{ label }}</view>
		</fui-form-item>
	</picker>
</template>

<script setup>
	import { ref, watch } from 'vue';
	import { fetchCities, fetchDepartments } from '@/common/api/index.js';

	const city_id = defineModel('city_id');
	const department_id = defineModel('department_id');

	const range = ref([]);
	const value = ref([]);

	getCities();
	async function getCities() {
		const { success, data } = await fetchCities();
		if (success) {
			range.value.splice(0, 1, data);
			if (data.length > 0) {
				getDepartments(data[0].id);
			}
		}
	}

	async function getDepartments(id) {
		const { success, data } = await fetchDepartments(id);
		if (success) {
			range.value.splice(1, 1, data);
		}
	}

	const columnchange = async ({ detail: { column, value } }) => {
		if (column === 0) {
			const id = range.value[0][value].id;
			await getDepartments(id);
		}
	};

	const change = (e) => {
		value.value = e.detail.value;
	};

	const label = ref('');
	watch(
		value,
		(val) => {
			if (val.length === 2) {
				const cityLabel = range.value[0][val[0]].name;
				const cityId = range.value[0][val[0]].id;
				const departmentLabel = range.value[1][val[1]].name;
				const departmentId = range.value[1][val[1]].id;
				label.value = `${cityLabel}--${departmentLabel}`;
				city_id.value = cityId;
				department_id.value = departmentId;
			}
		}, { immediate: true }
	);

	watch(
		[city_id, department_id],
		async ([val1, val2]) => {
			if (value.value.length === 0 && val1 && val2) {
				await getCities();
				const val1Index = range.value[0].findIndex((em) => em.id === val1);
				await getDepartments(val1);
				const val2Index = range.value[1].findIndex((em) => em.id === val2);
				value.value = [val1Index, val2Index];
			}
		}, { immediate: true }
	);
</script>

<style></style>